<template>
    <avue-crud ref="crud"
               :page.sync="page"
               :data="tableData"
               :table-loading="tableLoading"
               :option="tableOption"
               @on-load="getList"
               @search-change="searchChange"
               @refresh-change="refreshChange"
               @row-update="handleUpdate"
               @row-save="handleSave"
               @selection-change="selectionChange">
        <template slot="menuLeft">
            <el-checkbox-group v-model="checkList">
                <el-checkbox label="计算库存" @change="countNum($event)"></el-checkbox>
                <el-checkbox label="计算损耗" @change="countLoss($event)"></el-checkbox>
            </el-checkbox-group>
        </template>
        <template slot="menuRight">
            <el-button type="primary" icon="el-icon-edit" size="small" @click="createPurchaseOrder">生成采购单</el-button>
        </template>
        <template slot-scope="scope" slot="menu">
            <el-button type="text"
                       size="small"
                       plain
                       @click="jumpToDetail(scope.row)">详情
            </el-button>
        </template>
    </avue-crud>
</template>

<script>
    import {
        fetchList,
        putObj,
        changeStatus,
        addObj,
        createPurchaseOrder as createOrder
    } from '@/api/scm/order/summary_order'
    import {
        tableOption
    } from '@/const/crud/scm/order/summary_order'
    import {
        mapGetters
    } from 'vuex'
    import {getStore, setStore} from "@/util/store";
    import Util from '@/util/pds/utils'


    let cookieUtil = new Util();

    export default {
        name: "needPurchase",
        data() {
            return {
                formLabelWidth: '',
                tableData: [],
                checkList: ['待采购商品'],
                page: {
                    total: 0, // 总页数
                    currentPage: 1, // 当前页数
                    pageSize: 20 // 每页显示多少条
                },
                tableLoading: false,
                //表格数据
                tableOption: tableOption,
                orderData: [],

                //列表参数定义
                summaryOrderId:'',
                buySeq:'',
                is_ture:false
            }
        },
        props: {
            // BuyOrder 等待时间
            minute: Number
        },
        computed: {
            // ...mapGetters(['permissions']),
            // permissionList() {
            //   return {
            //     addBtn: this.vaildData(this.permissions.purchase_purchasetask_add, true),
            //     delBtn: this.vaildData(this.permissions.purchase_purchasetask_del, true),
            //     editBtn: this.vaildData(this.permissions.purchase_purchasetask_edit, true)
            //   };
            // }
        },
        methods: {
            getList(page, params = {}) {
                let pmId = getStore({name: "pmId"});
                // 更新 采购单状态
                changeStatus({
                    pmId: pmId,
                    minute: this.minute
                }).then(res => {
                    console.log(" 更新 采购单状态", res.data);
                });

                params.pmId = pmId;
                // 默认配送日期
                if (!params.deliveryTime) {
                    params.deliveryTime = cookieUtil.getDiffDate(1);
                }
                this.tableLoading = true
                fetchList(params).then(res => {
                    this.tableLoading = false
                    // console.log(" 更新 列表", response);
                    if (res.data.code === 0) {
                        res.data.data.forEach(item => {
                          item.purchaseNum = item.needBuyNum
                        })
                        this.tableData = res.data.data
                        // this.page.total = response.data.data.total
                    }
                }).catch(e => {
                    this.tableLoading = false
                    this.tableData = [];
                });
            },
            //计算库存
            countNum(e){
              if(e == true){
                this.is_ture = true;
                this.tableData.forEach(item => {
                  item.purchaseNum = item.needBuyNum - item.goodsStorage
                })
              }else{
                this.is_ture = false;
                this.tableData.forEach(item => {
                  item.purchaseNum = item.needBuyNum
                })
              }
              console.log(this.tableData);
            },
            //计算损耗
            countLoss(e){
              if(e == true){
                this.tableData.forEach(item => {
                  item.purchaseNum = item.purchaseNum* (1+item.lossRate);
                })
              }else{
                this.tableData.forEach(item => {
                  item.purchaseNum = item.needBuyNum
                })
              }
            },
            /**
             * @title 数据更新
             * @param row 为当前的数据
             * @param index 为当前更新数据的行数
             * @param done 为表单关闭函数
             *
             **/
            handleUpdate: function (row, index, done) {
                putObj(row).then(data => {
                    this.tableData.splice(index, 1, Object.assign({}, row))
                    this.$message({
                        showClose: true,
                        message: '修改成功',
                        type: 'success'
                    })
                    done()
                    this.getList(this.page)
                })
            },
            /**
             * @title 数据添加
             * @param row 为当前的数据
             * @param done 为表单关闭函数
             *
             **/
            handleSave: function (row, done) {
                addObj(row).then(data => {
                    this.tableData.push(Object.assign({}, row))
                    this.$message({
                        showClose: true,
                        message: '添加成功',
                        type: 'success'
                    })
                    done()
                    this.getList(this.page)
                })
            },
            //移除
            handleClick(row) {
                console.log(row);
            },
            /**
             * 搜索回调
             */
            searchChange(form, done) {
                this.getList(this.page, form);
                done();
            },
            /**
             * 刷新回调
             */
            refreshChange(info) {
    this.getList(this.page, this.filterForm(info.searchForm));
},
            /**
             * 生成采购单
             */
            createPurchaseOrder() {
                if(this.orderData.length){
                    let summaryList = [];
                    for(var i in this.orderData){
                      if(this.is_ture == true){
                        this.orderData[i].needBuyNum = this.orderData[i].purchaseNum
                      }
                      summaryList.push({id:this.orderData[i].id,
                        buySeq:this.orderData[i].buySeq,
                        goodsModelId:this.orderData[i].goodsModelId,
                        deliveryTime:this.orderData[i].deliveryTime,
                        needBuyNum:this.orderData[i].needBuyNum,
                      })
                    }
                    let params = {
                      pmId:getStore({name: "pmId"}),
                      summaryList:summaryList
                    }
                    createOrder(params).then(res=>{
                      if(res.data.code==0){
                        this.$message.success("生成成功");
                        this.getList(this.page);
                        let query = {
                          purchaseSn:res.data.data.purchaseSn,
                        }
                        this.$router.push({path: '/purchase_order/launch', query: query})
                      }else{
                        this.$message.success("生成失败");
                      }
                    });
                    return false
                }else{
                  this.$message({
                    showClose: true,
                    message: '请先选择',
                    type: 'error'
                  })
                }
            },
            saveSummaryOrder(obj) {
                addObj(obj).then(data => {
                    this.$message({
                        showClose: true,
                        message: '添加成功',
                        type: 'success'
                    })
                })
            },

            jumpToDetail(row) {
                let query = {
                  // goodsModelId: row.goodsModelId,
                  // buySeq: row.buySeq,
                  // deliveryTime: row.deliveryTime,
                  // summaryOrderId: row.summaryOrderId,
                  row:row

                }
                this.$router.push({path: '/summary_order/needpurchasedetail',query:query});
            },

            selectionChange(list) {
                this.orderData = list
            }
        }
    }
</script>

<style scoped>

</style>
